package handles

import (
	"errors"
	"path/filepath"
	"sort"
	"strconv"
	"strings"

	"github.com/alist-org/alist/v3/internal/aria2"
	"github.com/alist-org/alist/v3/internal/fs"
	"github.com/alist-org/alist/v3/internal/qbittorrent"
	"github.com/alist-org/alist/v3/pkg/task"
	"github.com/alist-org/alist/v3/server/common"
	"github.com/gin-gonic/gin"
)

type TaskInfo struct {
	ID       string `json:"id"`
	Name     string `json:"name"`
	State    string `json:"state"`
	Status   string `json:"status"`
	Progress int    `json:"progress"`
	Error    string `json:"error"`
}

type TaskKeyInfo struct {
	ID       string `json:"id"`
	Name     string `json:"name"`
	SrcPath  string `json:"src_path"`
	DstPath  string `json:"dst_path"`
	BasePath string `json:"base_path"`
	IsDir    bool   `json:"is_dir"`
	Size     int64  `json:"size"`
	Speed    int64  `json:"speed"`
	State    string `json:"state"`
	Status   string `json:"status"`
	Progress int    `json:"progress"`
	Error    string `json:"error"`
}

type K2Str[K comparable] func(k K) string

func uint64K2Str(k uint64) string {
	return strconv.FormatUint(k, 10)
}

func strK2Str(str string) string {
	return str
}

func getTaskInfo[K comparable](task *task.Task[K], k2Str K2Str[K]) TaskInfo {
	return TaskInfo{
		ID:       k2Str(task.ID),
		Name:     task.Name,
		State:    task.GetState(),
		Status:   task.GetStatus(),
		Progress: task.GetProgress(),
		Error:    task.GetErrMsg(),
	}
}

func getTaskKeyInfo[K comparable](task *task.Task[K], k2Str K2Str[K]) *TaskKeyInfo {
	return &TaskKeyInfo{
		ID:       k2Str(task.ID),
		Name:     task.Name,
		SrcPath:  task.SrcPath,
		DstPath:  task.DstPath,
		BasePath: task.BasePath,
		Size:     task.Size,
		IsDir:    false,
		Speed:    task.GetSpeed(),
		State:    task.GetState(),
		Status:   task.GetStatus(),
		Progress: task.GetProgress(),
		Error:    task.GetErrMsg(),
	}
}

func getTaskInfos[K comparable](tasks []*task.Task[K], k2Str K2Str[K]) []TaskInfo {
	var infos []TaskInfo
	for _, t := range tasks {
		infos = append(infos, getTaskInfo(t, k2Str))
	}
	return infos
}

func getTaskKeyInfos[K comparable](tasks []*task.Task[K], k2Str K2Str[K]) []*TaskKeyInfo {
	var infos []*TaskKeyInfo
	for _, t := range tasks {
		infos = append(infos, getTaskKeyInfo(t, k2Str))
	}
	return infos
}

func mergeTaskDir(list []*TaskKeyInfo) []*TaskKeyInfo {
	taskMap := make(map[string][]*TaskKeyInfo, 0)
	for _, v := range list {
		//key := filepath.Dir(v.SrcPath) + v.DstPath
		key := v.BasePath
		if _, ok := taskMap[key]; !ok {
			taskMap[key] = make([]*TaskKeyInfo, 1)
			taskMap[key][0] = v
			continue
		}
		taskMap[key] = append(taskMap[key], v)
	}
	resp := make([]*TaskKeyInfo, 0)
	for _, l := range taskMap {
		if len(l) == 1 {
			resp = append(resp, l[0])
			continue
		}
		resp = append(resp, mergeData(l))

	}
	return resp
}

func mergeData(l []*TaskKeyInfo) *TaskKeyInfo {
	t := new(TaskKeyInfo)
	t.IsDir = true
	t.SrcPath = l[0].BasePath
	t.DstPath = l[0].DstPath
	t.BasePath = l[0].BasePath

	var size int64 = 0
	var total = 0
	var progress = 0
	for _, val := range l {
		if t.ID == "" {
			t.ID = val.ID
		} else {
			t.ID += "," + val.ID
		}
		t.Speed += val.Speed
		dstDir := filepath.Dir(val.DstPath)
		if len(dstDir) < len(t.DstPath) {
			t.DstPath = dstDir
		}
		size += val.Size
		if val.State == task.PENDING || val.State == task.RUNNING {
			t.State = task.RUNNING
			total += 100
			progress += val.Progress
		}
		if val.Error != "" {
			t.Error += val.Error
		}
	}
	//t.Name = fmt.Sprintf("from dir : %s to dir : %s", t.BasePath, t.DstPath)
	t.Name = filepath.Base(t.BasePath)
	t.Size = size
	if total == 0 {
		t.Progress = 100
		t.State = task.SUCCEEDED
	} else {
		t.Progress = int(float32(progress) / float32(total) * 100.0)
	}
	return t
}

type Str2K[K comparable] func(str string) (K, error)

func str2Uint64K(str string) (uint64, error) {
	return strconv.ParseUint(str, 10, 64)
}

func str2StrK(str string) (string, error) {
	return str, nil
}

func taskRoute[K comparable](g *gin.RouterGroup, manager *task.Manager[K], k2Str K2Str[K], str2K Str2K[K]) {
	g.GET("/undone", func(c *gin.Context) {
		common.SuccessResp(c, getTaskInfos(manager.ListUndone(), k2Str))
	})
	g.GET("/done", func(c *gin.Context) {
		common.SuccessResp(c, getTaskInfos(manager.ListDone(), k2Str))
	})
	g.GET("/all", func(c *gin.Context) {
		k := c.Query("key")
		if k == "" {
			common.ErrorResp(c, errors.New("key is empty!!!"), 400)
			return
		}
		list := mergeTaskDir(getTaskKeyInfos(manager.ListByKey(k), k2Str))
		if len(list) == 0 {
			common.SuccessResp(c, make([]struct{}, 0))
			return
		}
		sort.SliceStable(list, func(i, j int) bool {
			if list[i].State == "running" && list[j].State != "running" {
				return true
			}
			if list[i].State != "running" && list[j].State == "running" {
				return false
			}
			return list[i].Size >= list[j].Size
		})
		common.SuccessResp(c, list)
	})
	g.POST("/cancel_all", func(c *gin.Context) {
		k := c.Query("key")
		if k == "" {
			common.ErrorResp(c, errors.New("key is empty!!!"), 400)
			return
		}
		manager.CancelAllByKey(k)
		common.SuccessResp(c)
	})
	g.POST("/clear_all", func(c *gin.Context) {
		k := c.Query("key")
		if k == "" {
			common.ErrorResp(c, errors.New("key is empty!!!"), 400)
			return
		}
		manager.CleanAllByKey(k)
		common.SuccessResp(c)
	})
	g.POST("/cancel", func(c *gin.Context) {
		tid := c.Query("tid")
		id, err := str2K(tid)
		if err != nil {
			common.ErrorResp(c, err, 400)
			return
		}
		if err := manager.Cancel(id); err != nil {
			common.ErrorResp(c, err, 500)
		} else {
			common.SuccessResp(c)
		}
	})
	g.POST("/delete", func(c *gin.Context) {
		tid := c.Query("tid")
		id, err := str2K(tid)
		if err != nil {
			common.ErrorResp(c, err, 400)
			return
		}
		if err := manager.Remove(id); err != nil {
			common.ErrorResp(c, err, 500)
		} else {
			common.SuccessResp(c)
		}
	})
	g.POST("/delete_batch", func(c *gin.Context) {
		tidList := c.Query("tids")
		list := strings.Split(tidList, ",")
		for _, val := range list {
			id, err := str2K(val)
			if err != nil {
				common.ErrorResp(c, err, 400)
				return
			}
			if err := manager.Remove(id); err != nil {
				common.ErrorResp(c, err, 500)
				return
			}
		}
		common.SuccessResp(c)
	})
	g.POST("/retry", func(c *gin.Context) {
		tid := c.Query("tid")
		id, err := str2K(tid)
		if err != nil {
			common.ErrorResp(c, err, 400)
			return
		}
		if err := manager.Retry(id); err != nil {
			common.ErrorResp(c, err, 500)
		} else {
			common.SuccessResp(c)
		}
	})
	g.POST("/clear_done", func(c *gin.Context) {
		manager.ClearDone()
		common.SuccessResp(c)
	})
	g.POST("/clear_succeeded", func(c *gin.Context) {
		manager.ClearSucceeded()
		common.SuccessResp(c)
	})
}

func SetupTaskRoute(g *gin.RouterGroup) {
	taskRoute(g.Group("/aria2_down"), aria2.DownTaskManager, strK2Str, str2StrK)
	taskRoute(g.Group("/aria2_transfer"), aria2.TransferTaskManager, uint64K2Str, str2Uint64K)
	taskRoute(g.Group("/upload"), fs.UploadTaskManager, uint64K2Str, str2Uint64K)
	taskRoute(g.Group("/copy"), fs.CopyTaskManager, uint64K2Str, str2Uint64K)
	taskRoute(g.Group("/qbit_down"), qbittorrent.DownTaskManager, strK2Str, str2StrK)
	taskRoute(g.Group("/qbit_transfer"), qbittorrent.TransferTaskManager, uint64K2Str, str2Uint64K)
}
